//
//  XZGroupDetailPopVC.m
//  Teecloud
//
//  Created by PC on 2018/11/26.
//  Copyright © 2018年 小志. All rights reserved.
//
#import "TZImagePickerController.h"
#import "GMChoseFileVC.h"
#import <KSPhotoBrowser/KSPhotoBrowser.h>
#import "XZGroupDetailPopVC.h"
#import "GMTextView.h"
#import "GMAudioView.h"
#import "GMPhotoCell.h"
#import "XZGroupDetailPopCell.h"
#import "GMFileModel.h"
#import "RecordHUD.h"
#import "D3RecordButton.h"

#import "ZJPickBaseView.h"
#import "ZJDatePickerView.h"
#import "ZJNormalPickerView.h"
#import "XZAcceptUsers.h"
#import "XZResList.h"
#import "XZChatTypeNames.h"
@interface XZGroupDetailPopVC ()<UICollectionViewDataSource,UICollectionViewDelegate,XMGWaterflowLayoutDelegate,TZImagePickerControllerDelegate,D3RecordDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet D3RecordButton *btn;
@property (weak, nonatomic) IBOutlet UIScrollView *scollview;
@property (weak, nonatomic) IBOutlet UIButton *changeBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tabHeight;

@property (weak, nonatomic) IBOutlet UIView *bagView;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) GMTextView *textView;
@property (nonatomic, strong) GMAudioView *audioView;
@property (nonatomic, assign) BOOL isAudio;
/**本地图片数组*/
@property (nonatomic, strong) NSMutableArray *imgArr;
@property(nonatomic,assign)NSInteger maxCount;//最多个数
/**上传到服务器的图片模型数组*/
@property (nonatomic, strong) NSMutableArray *netImgArr;
/**本地语音*/
@property (nonatomic, strong) NSMutableArray *audioArr;
/**上传到服务器的语音数组*/
@property (nonatomic, strong) NSMutableArray *netaudioArr;


@property (nonatomic, strong) NSMutableArray *typeArr;
@property (nonatomic, copy) NSString *chatTypeNeme;//:消息类别代码名称
@property (nonatomic, copy) NSString *startDate;//周开始日期
@property (nonatomic, copy) NSString *endDate;//:周结束日期
@property (nonatomic, copy) NSString *month;//月份
@property (nonatomic, copy) NSString *acceptUserId;//接收用户id
@property (nonatomic, copy) NSString *acceptName;//接收用户姓名
@property (nonatomic, copy) NSString *shareFlag;//0不分享，1分享
@property (nonatomic, copy) NSString *taskResId;//关联任务资源id
@property (nonatomic, copy) NSString *taskResName;//关联任务资源姓名
@property (nonatomic, copy) NSString *gradeScoreValue;//评级或评分
@end
#define TypeCell @"XZGroupDetailPopCell"
@implementation XZGroupDetailPopVC
-(void)dealloc{
    XZLog(@"%s",__FUNCTION__);
    /**页面销毁的时候移除通知*/
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.textView.isNotStar = NO;
    self.maxCount = 5;/**设置最大图片数量*/
    self.scollview.scrollEnabled = false;
    self.scollview.contentSize = CGSizeMake(DEVICE_WIDTH*2, 0);
    [self.scollview addSubview:self.textView];
    [self.scollview addSubview:self.audioView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"GMPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"GMPhotoCell"];
    [_btn initRecord:self maxtime:120 title:@"上滑取消录音"];
    self.btn.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataBtnSatate) name:@"updataBtn" object:nil];
    
    //tableView的属性
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = false;
    self.tableView.showsVerticalScrollIndicator= false;
    self.tableView.showsHorizontalScrollIndicator =false;
    [self.tableView registerNib:[UINib nibWithNibName:@"XZGroupDetailPopCell" bundle:nil] forCellReuseIdentifier:TypeCell];
    
    //可选项来自GroupConfig.ChatTypeNames，当可选项数=1时自动选中并隐藏本选择项；>1时自动选中ChatType=1的项；
    if (self.model.GroupConfig.ChatTypeNames.count > 1) {
        self.tabHeight.constant = 30.f;
        XZChatTypeNames *chatTypeNames = self.model.GroupConfig.ChatTypeNames.firstObject;
        NSDictionary *typeDict = @{
                                   @"type":@"类别",
                                   @"typeDetail":chatTypeNames.Name
                                   };
        self.chatTypeNeme =chatTypeNames.Name;
        [self.typeArr addObject:typeDict];
    }else{
        XZChatTypeNames *chatTypeNames = self.model.GroupConfig.ChatTypeNames.firstObject;
        self.chatTypeNeme =chatTypeNames.Name;
        self.tabHeight.constant = 0.f;
    }
    //0不分享（默认选择)
    self.shareFlag = @"0";
}

-(void)endRecord:(NSData *)voiceData{
    [self.audioArr addObject:voiceData];
    self.audioView.dataArr = self.audioArr;
    if (self.audioArr.count >2) {
        self.btn.backgroundColor = kDarkGrayColor;
        [self.btn setTitle:@"限制录制三段语音" forState:UIControlStateNormal];
        self.btn.userInteractionEnabled = NO;
    }else{
        self.btn.backgroundColor = [UIColor colorWithHexString:@"007AFF"];
        [self.btn setTitle:@"长按录音" forState:UIControlStateNormal];
        self.btn.userInteractionEnabled = YES;
    }
}
-(void)updataBtnSatate{
    self.btn.backgroundColor = [UIColor colorWithHexString:@"007AFF"];
    [self.btn setTitle:@"长按录音" forState:UIControlStateNormal];
    self.btn.userInteractionEnabled = YES;
}
#pragma mark - Setter
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        //1.初始化layout
        // 创建布局
        XMGWaterflowLayout *layout = [[XMGWaterflowLayout alloc] init];
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH-30, 80) collectionViewLayout:layout];
        _collectionView.backgroundColor = kWhiteColor;
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
        _collectionView.delegate = self;
        [self.bagView addSubview:_collectionView];
        
    }
    return _collectionView;
}
- (NSMutableArray *)typeArr{
    if (!_typeArr) {
        _typeArr = [[NSMutableArray alloc]init];
    }
    return _typeArr;
}
-(NSMutableArray *)netaudioArr{
    if (!_netaudioArr) {
        _netaudioArr = [[NSMutableArray alloc] init];
    }
    return _netaudioArr;
}
-(NSMutableArray *)audioArr{
    if (!_audioArr) {
        _audioArr = [[NSMutableArray alloc] init];
    }
    return _audioArr;
}
-(NSMutableArray *)netImgArr{
    if (!_netImgArr) {
        _netImgArr = [[NSMutableArray alloc] init];
    }
    return _netImgArr;
}
-(NSMutableArray *)imgArr{
    if (!_imgArr) {
        _imgArr = [[NSMutableArray alloc] init];
    }
    return _imgArr;
}
-(GMTextView *)textView{
    if (!_textView) {
        _textView = [GMTextView viewFromXib];
        _textView.isNotStar = NO;
        _textView.frame = CGRectMake(0, 0, DEVICE_WIDTH, 130);
    }
    return _textView;
}
-(GMAudioView *)audioView{
    if (!_audioView) {
        _audioView = [GMAudioView viewFromXib];
        _audioView.frame = CGRectMake(DEVICE_WIDTH, 0, DEVICE_WIDTH, 130);
    }
    return _audioView;
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imgArr.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GMPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GMPhotoCell" forIndexPath:indexPath];
    if (indexPath.row == self.imgArr.count || self.imgArr.count == 0) {
        cell.photoImg.image = [UIImage imageNamed:@"photo_add"];
        cell.delectBtn.hidden=YES;
    }else{
        NSDictionary *dict = self.imgArr[indexPath.row];
        NSString *name =[dict objectForKey:@"name"];
        if (kIsEmptyString(name)) {
            cell.photoImg.image = [dict objectForKey:@"image"];
        }else{
            cell.photoImg.image =[UIImage imageNamed:[dict objectForKey:@"image"]];
        }
        cell.delectBtn.hidden=NO;
        cell.delectBtn.tag = indexPath.row +1000;
        [cell.delectBtn addTarget:self action:@selector(delectImageWithBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
#pragma mark - <XMGWaterflowLayoutDelegate>
- (CGFloat)waterflowLayout:(XMGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth{
    //计算item的高度
    return itemWidth;
}

- (CGFloat)rowMarginInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 10;
}
/**返回每行的个数*/
- (CGFloat)columnCountInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return 5;
}

- (UIEdgeInsets)edgeInsetsInWaterflowLayout:(XMGWaterflowLayout *)waterflowLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    kWeakObject(self)
    if (indexPath.row == self.imgArr.count) {
        
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                                 NSLog(@"action = %@", action);
                                                             }];
        UIAlertAction* manAction = [UIAlertAction actionWithTitle:@"选择文件" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              GMChoseFileVC *chose = [[GMChoseFileVC alloc] init];
                                                              chose.GMChoseFileVCBlock = ^(NSDictionary *dict) {
                                                                  [weakself.imgArr addObject:dict];
                                                                  [weakself.collectionView reloadData];
                                                              };
                                                              [self presentViewController:chose animated:YES completion:nil];
                                                          }];
        UIAlertAction* womanAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault
                                                            handler:^(UIAlertAction * action) {
                                                                //响应事件
                                                                TZImagePickerController *pickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:self.maxCount - self.imgArr.count delegate:self];
                                                                pickerController.sortAscendingByModificationDate = NO;
                                                                pickerController.showPhotoCannotSelectLayer = YES;
                                                                kWeakObject(self)
                                                                [pickerController setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray *assets, BOOL isSelectOriginalPhoto){
                                                                    
                                                                    if (photo.count) {
                                                                        [weakself addNewImages:photo];
                                                                    }
                                                                }];
                                                                [self presentViewController:pickerController animated:YES completion:nil];
                                                            }];
        [alert addAction:cancelAction];
        [alert addAction:manAction];
        [alert addAction:womanAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}
//添加多张图片--
-(void)addNewImages:(NSArray *)newImages{
    
    //默认多张图片选择顺序是按照用户选择顺序，所以这里进行反序，因为后面把刚添加的index 置为0；
    NSArray* images = [[newImages reverseObjectEnumerator] allObjects];
    [images enumerateObjectsUsingBlock:^(UIImage * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *imgDict = @{@"image":obj};
        [self.imgArr insertObject:imgDict atIndex:0];
        
    }];
    [self.collectionView reloadData];
    //先从服务器获取OSS需要的数据
    
}
- (void)delectImageWithBtn:(UIButton *)sender{
    NSInteger index =sender.tag -1000;
    [self.imgArr removeObjectAtIndex:index];
    [self.collectionView reloadData];
}

#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.typeArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.typeArr[indexPath.row];
    NSString *type = dict[@"type"];
    NSString *typeDetail = dict[@"typeDetail"];
    XZGroupDetailPopCell *typeCell = [tableView dequeueReusableCellWithIdentifier:TypeCell];
    typeCell.nameLabel.text = typeDetail;
    typeCell.styleLabel.text =type;
    return typeCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    NSDictionary *dict = self.typeArr[indexPath.row];
    NSString *type = dict[@"type"];
    if ([type isEqualToString:@"类别"]) {
        kWeakObject(self)
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"选择类别"
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //取消
                                                             }];
        
        
        [alert addAction:cancelAction];
        for (XZChatTypeNames *chatTypeNames in self.model.GroupConfig.ChatTypeNames) {
            UIAlertAction* action = [UIAlertAction actionWithTitle:chatTypeNames.Name style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               //响应事件
                                                               [weakself setArray:action.title];
                                                               weakself.chatTypeNeme = action.title;
                                                           }];
            [alert addAction:action];
        }
        [self presentViewController:alert animated:YES completion:nil];
    }else if ([type isEqualToString:@"开始"]){
        kWeakObject(self)
        [ZJDatePickerView zj_showDatePickerWithTitle:@"请选周开始时间" dateType:ZJDatePickerModeYMD defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
            NSDictionary *satrTime = @{
                                       @"type":@"开始",
                                       @"typeDetail":selectValue
                                       };
            //开始周期
            self.startDate = selectValue;
            [weakself.typeArr replaceObjectAtIndex:1 withObject:satrTime];
            //选择t2后当t3为空时（未选择）t3自动设置为t2+4天，用户可更改；
            NSString *afterWeekTime = [weakself getBeforeYear:0 month:0 day:4 currentTime:selectValue];
            //结束周期
            self.endDate = afterWeekTime;
            NSDictionary *endTime = @{
                                      @"type":@"结束",
                                      @"typeDetail":afterWeekTime
                                      };
            [weakself.typeArr replaceObjectAtIndex:2 withObject:endTime];
            [weakself.tableView reloadData];
        } cancelBlock:^{
            
        }];
    }else if ([type isEqualToString:@"结束"]){
        kWeakObject(self)
        [ZJDatePickerView zj_showDatePickerWithTitle:@"请选周结束时间" dateType:ZJDatePickerModeYMD defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
            NSDictionary *endTime = @{
                                      @"type":@"结束",
                                      @"typeDetail":selectValue
                                      };
            //结束周期
            self.endDate = selectValue;
            [weakself.typeArr replaceObjectAtIndex:2 withObject:endTime];
            [weakself.tableView reloadData];
        } cancelBlock:^{
            
        }];
    }else if ([type isEqualToString:@"月份"]){
        kWeakObject(self)
        [ZJDatePickerView zj_showDatePickerWithTitle:@"请选月份" dateType:ZJDatePickerModeYM defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:YES lineColor:kDarkGrayColor rowHeight:40 resultBlock:^(NSString *selectValue) {
            NSDictionary *endTime = @{
                                      @"type":@"月份",
                                      @"typeDetail":selectValue
                                      };
            //月份格式2018年01月
            NSString *year = [selectValue substringToIndex:4];
            NSString *mooth = [selectValue substringFromIndex:5];
            self.month = [NSString stringWithFormat:@"%@年%@月",year,mooth];
            [weakself.typeArr replaceObjectAtIndex:1 withObject:endTime];
            [weakself.tableView reloadData];
        } cancelBlock:^{
            
        }];
    }else if ([type isEqualToString:@"任务"]){
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"选择任务"
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //取消
                                                             }];
        
        
        [alert addAction:cancelAction];
        for (XZResList *resList in self.model.ResList) {
            UIAlertAction* action = [UIAlertAction actionWithTitle:resList.Name style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               NSDictionary *accept = @{
                                                                                        @"type":@"任务",
                                                                                        @"typeDetail":action.title
                                                                                        };
                                                               //接收人的姓名
                                                               self.taskResName = action.title;
                                                               [self.typeArr replaceObjectAtIndex:self.typeArr.count - 3 withObject:accept];
                                                               [self.tableView reloadData];
                                                           }];
            [alert addAction:action];
        }
        
        
        [self presentViewController:alert animated:YES completion:nil];
    }else if ([type isEqualToString:@"接收"]){
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"选择接收人"
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 //取消
                                                             }];
        
        
        [alert addAction:cancelAction];
        for (XZAcceptUsers *acceptUsers in self.model.GroupConfig.AcceptUsers) {
            UIAlertAction* action = [UIAlertAction actionWithTitle:acceptUsers.Name style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               NSDictionary *accept = @{
                                                                                        @"type":@"接收",
                                                                                        @"typeDetail":action.title
                                                                                        };
                                                               //接收人的姓名
                                                               self.acceptName = action.title;
                                                               [self.typeArr replaceObjectAtIndex:self.typeArr.count - 2 withObject:accept];
                                                               [self.tableView reloadData];
                                                           }];
            [alert addAction:action];
        }
        [self presentViewController:alert animated:YES completion:nil];
    }else if ([type isEqualToString:@"分享"]){
        //显示弹出框列表选择
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"选择分享"
                                                                       message:nil
                                                                preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 XZLog(@"action = %@", action);
                                                             }];
        UIAlertAction* noShare = [UIAlertAction actionWithTitle:@"不分享" style:UIAlertActionStyleDefault
                                                        handler:^(UIAlertAction * action) {
                                                            //响应事件
                                                            self.shareFlag = @"0";
                                                            NSDictionary *shareStype = @{
                                                                                         @"type":@"分享",
                                                                                         @"typeDetail":@"不分享"
                                                                                         };
                                                            [self.typeArr replaceObjectAtIndex:self.typeArr.count-1 withObject:shareStype];
                                                            [self.tableView reloadData];
                                                        }];
        
        UIAlertAction* share = [UIAlertAction actionWithTitle:@"分享" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          //响应事件
                                                          self.shareFlag = @"1";
                                                          NSDictionary *shareStype = @{
                                                                                       @"type":@"分享",
                                                                                       @"typeDetail":@"分享"
                                                                                       };
                                                          [self.typeArr replaceObjectAtIndex:self.typeArr.count-1 withObject:shareStype];
                                                          [self.tableView reloadData];
                                                      }];
        
        [alert addAction:cancelAction];
        [alert addAction:noShare];
        [alert addAction:share];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
/**
 获取当前日期的后面日期
 
 @param year 年
 @param month 月
 @param day 日
 @return 日期
 */
- (NSString *)getBeforeYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day currentTime:(NSString *)currentTime{
    //得到当前的时间
    NSDate * mydate = [NSDate dateWithString:currentTime format:@"yyyy-MM-dd"];
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:year];
    [adcomps setMonth:month];
    [adcomps setDay:day];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    return beforDate;
}
/**
 根据选中的type类型来构建数据源
 
 @param selectType 类别名称
 */
- (void)setArray:(NSString *)selectType{
    [self.typeArr removeAllObjects];
    for (XZChatTypeNames *chatTypeNames in self.model.GroupConfig.ChatTypeNames) {
        if ([selectType isEqualToString:chatTypeNames.Name]) {
            if ([chatTypeNames.ChatType isEqualToString:@"1"]) {
                NSDictionary *typeDict = @{
                                           @"type":@"类别",
                                           @"typeDetail":chatTypeNames.Name
                                           };
                self.tabHeight.constant = 30.f;
                [self.typeArr addObject:typeDict];
            }else if ([chatTypeNames.ChatType isEqualToString:@"2"] ||[chatTypeNames.ChatType isEqualToString:@"4"]||[chatTypeNames.ChatType isEqualToString:@"5"]){
                self.tabHeight.constant = 120.f;
                NSDictionary *typeDict = @{
                                           @"type":@"类别",
                                           @"typeDetail":chatTypeNames.Name
                                           };
                NSDictionary *task = @{
                                       @"type":@"任务",
                                       @"typeDetail":@"请选接关联任务(非必选)"
                                       };
                NSDictionary *accept = @{
                                         @"type":@"接收",
                                         @"typeDetail":@"请选接收人"
                                         };
                NSDictionary *share = @{
                                        @"type":@"分享",
                                        @"typeDetail":@"请选接分享方式"
                                        };
                
                [self.typeArr addObject:typeDict];
                [self.typeArr addObject:task];
                [self.typeArr addObject:accept];
                [self.typeArr addObject:share];
            }else if ([chatTypeNames.ChatType isEqualToString:@"3"]||[chatTypeNames.ChatType isEqualToString:@"8"]){
                self.tabHeight.constant =90.f;
                NSDictionary *typeDict = @{
                                           @"type":@"类别",
                                           @"typeDetail":chatTypeNames.Name
                                           };
                NSDictionary *accept = @{
                                         @"type":@"接收",
                                         @"typeDetail":@"请选接收人"
                                         };
                NSDictionary *share = @{
                                        @"type":@"分享",
                                        @"typeDetail":@"请选接分享方式"
                                        };
                [self.typeArr addObject:typeDict];
                [self.typeArr addObject:accept];
                [self.typeArr addObject:share];
            }else if ([chatTypeNames.ChatType isEqualToString:@"6"]){
                self.tabHeight.constant = 150.f;
                NSDictionary *typeDict = @{
                                           @"type":@"类别",
                                           @"typeDetail":chatTypeNames.Name
                                           };
                NSDictionary *starTime = @{
                                           @"type":@"开始",
                                           @"typeDetail":@"请选择周开始日期"
                                           };
                NSDictionary *endTime = @{
                                          @"type":@"结束",
                                          @"typeDetail":@"请选择周结束日期"
                                          };
                NSDictionary *accept = @{
                                         @"type":@"接收",
                                         @"typeDetail":@"请选接收人"
                                         };
                
                NSDictionary *share = @{
                                        @"type":@"分享",
                                        @"typeDetail":@"请选接分享方式"
                                        };
                [self.typeArr addObject:typeDict];
                [self.typeArr addObject:starTime];
                [self.typeArr addObject:endTime];
                [self.typeArr addObject:accept];
                [self.typeArr addObject:share];
                
            }else if ([chatTypeNames.ChatType isEqualToString:@"7"]){
                self.tabHeight.constant = 120.f;
                NSDictionary *typeDict = @{
                                           @"type":@"类别",
                                           @"typeDetail":chatTypeNames.Name
                                           };
                NSDictionary *moonth = @{
                                         @"type":@"月份",
                                         @"typeDetail":@"请选择月份"
                                         };
                
                NSDictionary *accept = @{
                                         @"type":@"接收",
                                         @"typeDetail":@"请选接收人"
                                         };
                
                NSDictionary *share = @{
                                        @"type":@"分享",
                                        @"typeDetail":@"请选接分享方式"
                                        };
                [self.typeArr addObject:typeDict];
                [self.typeArr addObject:moonth];
                [self.typeArr addObject:accept];
                [self.typeArr addObject:share];
                
            }
        }
    }
    [self.tableView reloadData];
}
/**
 取消
 
 @param sender 取消按钮
 */
- (IBAction)cancleButtonAction:(UIButton *)sender {
    UIViewController * parent = [self.view containingViewController];
    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
        [parent dismissSemiModalView];
    }
}


/**
 切换语音或者文本按钮
 
 @param sender 按钮
 */
- (IBAction)changeViewButtonAction:(UIButton *)sender {
    if (self.isAudio) {
        self.btn.hidden = YES;
        self.scollview.contentOffset = CGPointMake(0, 0);
        [self.changeBtn setImage:[UIImage imageNamed:@"microphone-gray"] forState:UIControlStateNormal];
    }else{
        self.btn.hidden = NO;
        self.scollview.contentOffset = CGPointMake(DEVICE_WIDTH, 0);
        [self.changeBtn setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
    }
    _isAudio = !_isAudio;
}


/**
 提交按钮
 
 @param sender 提交按钮
 */
- (IBAction)submitButtonAction:(UIButton *)sender {
    //语音文本必须输入一样
    if (!(self.audioArr.count>0) && !(self.textView.textView.text.length > 0)) {
        [MBProgressHUD showErrorOrSuc:@"请提供文本消息或语音消息" toView:self.view];
        return;
    }
    dispatch_group_t uploadGroup = dispatch_group_create();
    for (NSInteger i =0; i<self.audioArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-remark"
                              };
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.mp3", dateString];
        [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:self.audioArr[i] name:@"audio_file" fileName:fileName mimeType:@"audio/mpeg" progress:^(NSProgress *progress) {
            
        } callback:^(id responseObject, NSError *error) {
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                    GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                    [self.netaudioArr addObject:model];
                    dispatch_group_leave(uploadGroup);
                }else{
                    /**显示错误信息*/
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                }
            }
        }];
    }
    for (NSInteger i =0; i<self.imgArr.count; i++) {
        dispatch_group_enter(uploadGroup);
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"fileType":@"res-remark"
                              };
        NSDictionary *temDict = self.imgArr[i];
        NSString *name =[temDict objectForKey:@"name"];
        UIImage *tempImg;
        if (kIsEmptyString(name)) {
            //上传图片
            tempImg = [temDict objectForKey:@"image"];
            NSData *imageData = UIImageJPEGRepresentation(tempImg, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg" progress:^(NSProgress *progress) {
                
            } callback:^(id responseObject, NSError *error) {
                if (!error) {
                    if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                        GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                        [self.netImgArr addObject:model];
                        dispatch_group_leave(uploadGroup);
                    }else{
                        /**显示错误信息*/
                        [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                    }
                }
            }];
        }else{
            //上传文件
            NSString *filePath = [temDict objectForKey:@"path"];
            NSData *fileData = [NSData dataWithContentsOfFile:filePath];
            NSString *fileName = [temDict objectForKey:@"name"];
            NSString *mimeType = @"";
            if ([fileName containsString:@"zip"]) {
                mimeType =@"application/zip";
            }else if ([fileName containsString:@"pdf"]) {
                mimeType =@"application/pdf";
            }else if ([fileName containsString:@"ppt"]) {
                mimeType =@"application/vnd.ms-powerpoint";
            }else if ([fileName containsString:@"docx"]) {
                mimeType =@"application/msword";
            }else if ([fileName containsString:@"excel"]) {
                mimeType =@"application/vnd.ms-excel";
            }else if ([fileName containsString:@"rar"]) {
                mimeType =@"application/x-rar-compressed";
            }else{
                mimeType =@"text/plain";
            }
            NSLog(@"%@",dict);
            [HJNetwork uploadImageURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UploadFile&$v=%@",VERSION] parameters:dict imageData:fileData name:@"file" fileName:fileName mimeType:mimeType progress:^(NSProgress *progress) {
                
            } callback:^(id responseObject, NSError *error) {
                if (!error) {
                    if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]){
                        GMFileModel *model = [GMFileModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                        [self.netImgArr addObject:model];
                        dispatch_group_leave(uploadGroup);
                    }else{
                        /**显示错误信息*/
                        [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
                    }
                }
            }];
        }
    }
    dispatch_group_notify(uploadGroup, dispatch_get_main_queue(), ^{
        [self sumbitAllData];
    });
}
-(void)sumbitAllData{
    NSString *imgFile1Id =@"";
    NSString *imgFile2Id =@"";
    NSString *imgFile3Id =@"";
    NSString *imgFile4Id =@"";
    NSString *imgFile5Id =@"";
    for (NSInteger i=0; i<self.netImgArr.count; i++) {
        GMFileModel *model =self.netImgArr[i];
        switch (i) {
            case 0:{
                imgFile1Id =model.Id;
            }
                break;
            case 1:{
                imgFile2Id =model.Id;
            }
                break;
            case 2:{
                imgFile3Id =model.Id;
            }
                break;
            case 3:{
                imgFile4Id =model.Id;
            }
                break;
            case 4:{
                imgFile5Id =model.Id;
            }
                break;
                
            default:
                break;
        }
    }
    NSString *voice1Id =@"";
    NSString *voice2Id=@"";
    NSString *voice3Id =@"";
    for (NSInteger i=0; i<self.netaudioArr.count; i++) {
        GMFileModel *model =self.netaudioArr[i];
        switch (i) {
            case 0:{
                voice1Id =model.Id;
            }
                break;
            case 1:{
                voice2Id =model.Id;
            }
                break;
            case 2:{
                voice3Id =model.Id;
            }
                break;
            default:
                break;
        }
    }
    
    //selectValue
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    
    [dict setValue:self.groupId forKey:@"groupId"];
    //消息类别代码
    for (XZChatTypeNames *chatTypeNames in self.model.GroupConfig.ChatTypeNames) {
        if ([self.chatTypeNeme isEqualToString:chatTypeNames.Name]) {
            [dict setValue:chatTypeNames.ChatType forKey:@"chatType"];
        }
    }
    //0 不分享，1 分享
    [dict setValue:self.shareFlag forKey:@"shareFlag"];
    //开始 结束周期时间
    [dict setValue:self.startDate forKey:@"startDate"];
    [dict setValue:self.endDate forKey:@"endDate"];
    //月份
    [dict setValue:self.month forKey:@"month"];
    //接收用户 Id
    for (XZAcceptUsers *acceptUsers in self.model.GroupConfig.AcceptUsers) {
        if ([self.acceptName isEqualToString:acceptUsers.Name]) {
             [dict setValue:acceptUsers.Id forKey:@"acceptUserId"];
        }
    }
    //关联任务资源id
    for (XZResList *resList in self.model.ResList) {
        if ([self.taskResName isEqualToString:resList.Name]) {
            [dict setValue:resList.Id forKey:@"taskResId"];
        }
    }
    
    [dict setValue:self.textView.textView.text?self.textView.textView.text:@"" forKey:@"content"];
    
    
    
    
    //图片
    [dict setValue:imgFile1Id forKey:@"imgFile1Id"];
    [dict setValue:imgFile2Id forKey:@"imgFile2Id"];
    [dict setValue:imgFile3Id forKey:@"imgFile3Id"];
    [dict setValue:imgFile4Id forKey:@"imgFile4Id"];
    [dict setValue:imgFile5Id forKey:@"imgFile5Id"];
    //语音
    [dict setValue:voice1Id forKey:@"voice1Id"];
    [dict setValue:voice2Id forKey:@"voice2Id"];
    [dict setValue:voice3Id forKey:@"voice3Id"];
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=PostGroupMsg&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                if (!kIsEmptyString(msg)) {
                    [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
                
                /*延迟执行时间2秒*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    /**发送通知刷新评论页面*/
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updatagroupMSG" object:nil];
                    UIViewController * parent = [weakself.view containingViewController];
                    if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
                        [parent dismissSemiModalView];
                    }
                });
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络出错" toView:weakself.view];
        }
    }];
}
@end
